//
//  SendDynamicViewController.m
//  ChatDemo-UI2.0
//
//  Created by syun on 16/10/27.
//  Copyright © 2016年 syun. All rights reserved.
//

#import "SendDynamicViewController.h"
#import "DropDownMenu.h"
#import "MenuButton.h"
#import "TZImagePickerController.h"

#import "XZPhotobrowserViewController.h"
#import "LSSelectPhotoMenuItem.h"
#import <AVFoundation/AVFoundation.h>
#import "ClassListTableViewCell.h"

@interface SendDynamicViewController ()<DropDownMenuDelegate,UITextFieldDelegate,UIActionSheetDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate,
TZImagePickerControllerDelegate,
LSSelectPhotoItemDelegate,
changeImageDelegate,UIAlertViewDelegate,UITextViewDelegate,UITableViewDataSource,UITableViewDelegate,UIGestureRecognizerDelegate>
{
    
    //照片选择器
    TZImagePickerController *imagePickerVc;
    
    UIButton *saveBtn;//发布按钮
    int height;//键盘高度
    
    UIToolbar * toolBarTopView;
    
    UIView *picLine;
    
    UIView *bottomView;
    
    NSMutableArray *imageArray;
    CGRect imageOrigalRect;
    
    NSString *lasttype;
    
    NSArray *_listArray;
}
@property (nonatomic, strong) UIImagePickerController *imagePicker;
@end

@implementation SendDynamicViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navBar.nav_titleLabel.text=@"发动态";
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithOriginalName:@"back"] style:UIBarButtonItemStyleDone target:self action:@selector(popout:)];
    [self.navigationItem setLeftBarButtonItem:backItem];
   
   
    self.navBar.rightButton.hidden = NO;
//    self.navBar.rightButton.enabled = NO;
    [self.navBar.rightButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 16, 0, 0)];
    [self.navBar.rightButton setTitle:@"发布" forState:UIControlStateNormal];
    [self.navBar.rightButton setTitleColor:RGBACOLOR(57, 173, 255, 1) forState:UIControlStateNormal];
    self.navBar.rightButton.titleLabel.font=[UIFont systemFontOfSize:16];
    [self.navBar.rightButton addTarget:self action:@selector(submitAction:) forControlEvents:UIControlEventTouchUpInside];
   
    
    SYAccount *accountDic = [SYAccountTool ShareAccount].account;
    
    lasttype = [NSString stringWithFormat:@"%d",accountDic.lasttype];
    
    [self initialize];
    
    [self loadClasses];
    
    [self loadTableView];
    
    [self keyBtn];
    
    [self creatUI];
    

    
    
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

-(void)keyBtn
{
    toolBarTopView = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 40)];
    [toolBarTopView setBarStyle:UIBarStyleDefault];
    toolBarTopView.backgroundColor=[UIColor whiteColor];
    UIBarButtonItem * btnSpace = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    
    UIBarButtonItem * doneBtn = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(dismissKeyBoard)];
    NSArray * buttonsArray = [NSArray arrayWithObjects:btnSpace,doneBtn,nil];
    [toolBarTopView setItems:buttonsArray];

}

-(void)dismissKeyBoard
{
    [ContentTextView resignFirstResponder];

    
    _BackScrollView.frame=CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, SCREENHEIGH-SafeAreaTopHeight);
    _BackScrollView.contentSize=CGSizeMake(SCREENWIDTH,  picsBackView.frame.origin.y+picsBackView.frame.size.height+20);
}
-(void)initialize{
    
    imageIdArray = [[NSMutableArray alloc] initWithCapacity:0];
    imageArray = [[NSMutableArray alloc] initWithCapacity:0];
    _listArray = [NSArray array];
    selcetArray=[NSMutableArray array];
    imageOrigalRect = _takePictureBtn.frame;
    
}
-(void)creatUI
{
    _BackScrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, SCREENHEIGH-SafeAreaTopHeight)];
    _BackScrollView.delegate=self;
    _BackScrollView.userInteractionEnabled=YES;
    _BackScrollView.scrollEnabled=YES;
    _BackScrollView.backgroundColor=RGBACOLOR(239, 239, 244, 1);
    [self.view addSubview:_BackScrollView];
    
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cancelKeyBoard:)];
    tap.delegate=self;
    [_BackScrollView addGestureRecognizer:tap];
    
    
    UIView *topView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 44)];
    topView.backgroundColor=[UIColor whiteColor];
    [_BackScrollView addSubview:topView];
    
    //班级标签
    ClassMarkLabel=[[UILabel alloc]initWithFrame:CGRectMake(12, 14, 70, 16)];
    ClassMarkLabel.text=@"可见班级";
    ClassMarkLabel.textColor=RGBACOLOR(59, 59, 59, 1);
    [topView addSubview:ClassMarkLabel];
    
    //箭头
    arrowImage=[[UIImageView alloc]initWithFrame:CGRectMake(SCREENWIDTH -18-12, 13, 18, 18)];
    arrowImage.backgroundColor=[UIColor whiteColor];
    arrowView.userInteractionEnabled = YES;
    arrowImage.image=[UIImage imageNamed:@"tianjia_sdh_nor"];
    [topView addSubview:arrowImage];
    
    
    //选择班级按钮
    selectClassBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    selectClassBtn.frame=CGRectMake(82, 0, SCREENWIDTH-82-12, 44);
    [selectClassBtn setTitleColor:RGBCOLOR(59, 59, 59) forState:UIControlStateNormal];
    [selectClassBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 15, 0, 0)];
    selectClassBtn.titleLabel.font=[UIFont systemFontOfSize:15];
    selectClassBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    selectClassBtn.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    [selectClassBtn addTarget:self action:@selector(openClassList:) forControlEvents:UIControlEventTouchUpInside];
    [_BackScrollView addSubview:selectClassBtn];
    
    
    bottomView=[[UIView alloc]initWithFrame:CGRectMake(0, 56, SCREENWIDTH, 233)];
    bottomView.backgroundColor=[UIColor whiteColor];
    [_BackScrollView addSubview:bottomView];
    
    //编辑内容
    ContentmarkLabel=[[UILabel alloc]initWithFrame:CGRectMake(12, 14,70, 16)];
    ContentmarkLabel.text=@"编辑内容";
    ContentmarkLabel.textColor=RGBACOLOR(59, 59, 59, 1);
    [bottomView addSubview:ContentmarkLabel];
    
    ContentTextView=[[UITextView alloc]initWithFrame:CGRectMake(82, 5, SCREENWIDTH-82-12, 205)];
    [ContentTextView setInputAccessoryView:toolBarTopView];
    ContentTextView.delegate=self;
    ContentTextView.userInteractionEnabled=YES;
    ContentTextView.backgroundColor=[UIColor whiteColor];
    ContentTextView.font=[UIFont systemFontOfSize:16];
    ContentTextView.text=@"请编辑动态内容";
    ContentTextView.textColor=RGBACOLOR(199, 199, 204, 1);
    [bottomView addSubview:ContentTextView];
    
    
    addPicView=[[UIView alloc]initWithFrame:CGRectMake(0, bottomView.frame.size.height-6-22, 97, 22)];
    
    [bottomView addSubview:addPicView];
    
    //相机图片
    PhotoPic=[[UIImageView alloc]initWithFrame:CGRectMake(12,2, 22, 22)];
    PhotoPic.userInteractionEnabled=YES;
    PhotoPic.image=[UIImage imageNamed:@"carmer_content_"];
//    PhotoPic.backgroundColor = [UIColor redColor];
    [addPicView addSubview:PhotoPic];
    
    
    //添加图片四个字
    MarkLabel=[[UILabel alloc]initWithFrame:CGRectMake(37, 8, 60, 14)];
    MarkLabel.text=@"添加图片";
    MarkLabel.textColor=RGBACOLOR(56, 173, 255, 1);
    MarkLabel.font=[UIFont systemFontOfSize:14];
//    MarkLabel.backgroundColor = [UIColor yellowColor];
    [addPicView addSubview:MarkLabel];
    
    //添加照片按钮
    addPic=[UIButton buttonWithType:UIButtonTypeCustom];
    addPic.frame=CGRectMake(0, bottomView.frame.size.height-6-17, 97,22);
    [addPic addTarget:self action:@selector(selectPics:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:addPic];
    
    
    
    WordCountLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, bottomView.frame.size.height-6-11, SCREENWIDTH-12, 11)];
    WordCountLabel.textColor=RGBACOLOR(199, 199, 204, 1);
    WordCountLabel.font=[UIFont systemFontOfSize:11];
    WordCountLabel.textAlignment=NSTextAlignmentRight;
    WordCountLabel.text=[NSString stringWithFormat:@"请将您的文字限制在200字以内 %@/200" ,@"0"];
//    WordCountLabel.backgroundColor = [UIColor blueColor];
    [bottomView addSubview:WordCountLabel];
    
    
    
    
    //照片
    picsBackView=[[UIView alloc]initWithFrame:CGRectMake(0, bottomView.frame.origin.y+bottomView.frame.size.height, SCREENWIDTH, 0)];
    picsBackView.backgroundColor=[UIColor whiteColor];
    [_BackScrollView addSubview:picsBackView];
    
    picLine =[[UIView alloc]initWithFrame:CGRectMake(12, 0, SCREENWIDTH-12, 0.5)];
    picLine.backgroundColor=RGBACOLOR(199, 199, 204, 1);
    [picsBackView addSubview:picLine];
    
    _takePictureBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    [_takePictureBtn addTarget:self action:@selector(selectPics:) forControlEvents:UIControlEventTouchUpInside];
    [_takePictureBtn setImage:[UIImage imageNamed:@"pic_content_"] forState:UIControlStateNormal];
    [picsBackView addSubview:_takePictureBtn];
    

    _BackScrollView.contentSize=CGSizeMake(SCREENWIDTH,  _takePictureBtn.frame.origin.y+_takePictureBtn.frame.size.height+20);
    
}
-(void)cancelKeyBoard:(UITapGestureRecognizer *)sender
{
    [ContentTextView resignFirstResponder];
}
- (void)openClassList:(UIButton *)sender
{
    [ContentTextView resignFirstResponder];
    
    UIWindow * window = KeyWindow;
    [window addSubview:classControl];
}

#pragma --tableViewdelegate
- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section {
    
    return [_listArray count];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *key=@"cell";
    ClassListTableViewCell *cell=(ClassListTableViewCell *)[tableView dequeueReusableCellWithIdentifier:key];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"ClassListTableViewCell" owner:self options:nil]objectAtIndex:0];
    }
    cell.backgroundColor=[UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.className.text=[[_listArray objectAtIndex:indexPath.row] objectForKey:@"classname"];
    
    if (selcetArray.count>0) {
        if ([[selcetArray objectAtIndex:indexPath.row]isEqualToString:@"no"]) {
            
            cell.className.textColor=[UIColor colorWithHexString:@"3b3b3b"];
            cell.chooseImage.image=[UIImage imageNamed:@"oa_menu_nor_"];
        }else
        {
            cell.className.textColor=[UIColor colorWithHexString:@"39adff"];
            cell.chooseImage.image=[UIImage imageNamed:@"oa_menu_press_"];
        }
    }
    
    cell.tag=indexPath.row+100;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ClassListTableViewCell *cell=[classTable cellForRowAtIndexPath:indexPath];//获取当前点击cell
    int i=(int)(cell.tag-100);
    if (selcetArray.count>0) {
        if ([[selcetArray objectAtIndex:i]isEqualToString:@"no"]) {
            [selcetArray replaceObjectAtIndex:i withObject:@"yes"];
            cell.className.textColor=[UIColor colorWithHexString:@"39adff"];
            cell.chooseImage.image=[UIImage imageNamed:@"oa_menu_press_"];
            classCount--;
        }else
        {
            [selcetArray replaceObjectAtIndex:i withObject:@"no"];
            cell.className.textColor=[UIColor colorWithHexString:@"3b3b3b"];
            cell.chooseImage.image=[UIImage imageNamed:@"oa_menu_nor_"];
            classCount++;
        }
    }
    
    if (classCount<selcetArray.count) {
        [chooseClass setImage:[UIImage imageNamed:@"sure_list_hl_"] forState:UIControlStateNormal];
    }else
    {
        [chooseClass setImage:[UIImage imageNamed:@"sure_list_nor_"] forState:UIControlStateNormal];
    }
}
-(void)loadTableView
{
    classControl=[[UIControl alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, SCREENHEIGH)];
    classControl.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"toumingbg"]];
    
    UIView *classView=[[UIView alloc]initWithFrame:CGRectMake(self.view.frame.size.width-152,50+ SafeAreaTopHeight, 140, 227)];
    classView.backgroundColor=[UIColor clearColor];
    
    UIImageView *classImageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, classView.frame.size.width, classView.frame.size.height)];
    classImageView.image=[UIImage imageNamed:@"listdrop_checkbox_four_"];
    [classView addSubview:classImageView];
    
    classTable=[[UITableView alloc]initWithFrame:CGRectMake(0, 9, classImageView.frame.size.width, classImageView.frame.size.height-40-9) style:UITableViewStylePlain];
    classTable.delegate=self;
    classTable.dataSource=self;
    classTable.backgroundColor=[UIColor clearColor];
    classTable.showsVerticalScrollIndicator =NO;
    [classTable setSeparatorColor:[UIColor clearColor]];
    
    chooseClass=[UIButton buttonWithType:UIButtonTypeCustom];
    chooseClass.frame=CGRectMake(40, classView.frame.size.height-32.5, 60, 25);
    [chooseClass setImage:[UIImage imageNamed:@"sure_list_nor_"] forState:UIControlStateNormal];
    [chooseClass addTarget: self action:@selector(chooseClassesAction:) forControlEvents:UIControlEventTouchUpInside];
    [classView addSubview:classTable];
    [classView addSubview:chooseClass];
    [classControl addSubview:classView];
    [classControl addTarget:self action:@selector(cancelClassList) forControlEvents:UIControlEventTouchUpInside];
    
}
-(void)popout:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    height = keyboardRect.size.height;
    
    _BackScrollView.frame=CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, SCREENHEIGH-SafeAreaTopHeight-height);
    _BackScrollView.contentSize=CGSizeMake(SCREENWIDTH,  _takePictureBtn.frame.origin.y+_takePictureBtn.frame.size.height+40);
}
//当键退出时调用

- (void)keyboardWillHide:(NSNotification *)aNotification

{
    
    _BackScrollView.frame=CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, SCREENHEIGH-SafeAreaTopHeight);
    _BackScrollView.contentSize=CGSizeMake(SCREENWIDTH,  _takePictureBtn.frame.origin.y+_takePictureBtn.frame.size.height+40);
}
-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma --选择图片
-(void)selectPics:(UIButton *)sender
{
    [ContentTextView resignFirstResponder];
   UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照上传",@"相册上传", nil];
   [actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
}
-(void)chooseClassesAction:(UIButton *)sender
{
    
    NSMutableArray *selcetClassArray=[NSMutableArray array];
    selcetClassidArray=[NSMutableArray array];
    AppDelegate * delegate = (AppDelegate *)CONSTAPPDELEGATE;
    for (int i=0; i<selcetArray.count; i++) {
        if ([[selcetArray objectAtIndex:i] isEqualToString:@"yes"]) {
            [selcetClassArray addObject:[[delegate.myClasses objectAtIndex:i] objectForKey:@"classename"]];
            [selcetClassidArray addObject:[[delegate.myClasses objectAtIndex:i] objectForKey:@"classid"]];
        }
    }
    NSString *classes=[selcetClassArray componentsJoinedByString:@","];
    [selectClassBtn setTitle:[NSString stringWithFormat:@" %@",classes] forState:UIControlStateNormal];
    [classControl removeFromSuperview];
    arrowImage.image=[UIImage imageNamed:@"tianjia_sdh_nor"];

}
-(void)cancelClassList
{
    [classControl removeFromSuperview];
    arrowImage.image=[UIImage imageNamed:@"tianjia_sdh_nor"];
}


-(void)loadClasses
{
        AppDelegate * delegate = (AppDelegate *)CONSTAPPDELEGATE;
        NSString *lasttype = [NSString stringWithFormat:@"%d",[SYAccountTool ShareAccount].account.lasttype];
        NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
        [dict setObject:@"api_classone_search" forKey:@"method"];
        [dict setObject:@"1" forKey:@"pageno"];
        [dict setObject:@"1000000000" forKey:@"pagesize"];
        [dict setObject:lasttype forKey:@"type"];
        [dict setObject:USERID forKey:@"userid"];
        [dict setObject:@"1" forKey:@"state"];
        [Utils getAllClass:nil parameters:dict success:^(NSInteger recode, id resposeJson){
        NSDictionary *dict = (NSDictionary *)resposeJson;
        delegate.myClasses = [dict objectForKey:@"re_data"];
        self->_listArray = delegate.myClasses;
        if (delegate.myClasses.count>0) {
            for (int i=0; i<delegate.myClasses.count; i++) {
                [self->selcetArray addObject:@"no"];
                
            }
            self->classCount=(int)self->selcetArray.count;
        }else
        {
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"请先创建/加入班级" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            alert.tag=111;
            [alert show];
            
        }
    
    
} failure:^(NSInteger recode, NSError * error){
    
}];
}

//发布
- (void)submitAction:(id)sender {
    
    
    if (selectClassBtn.titleLabel.text.length == 0) {
        [Utils alertViewWithMessage:@"请选择班级"];
        return;
    }
    
    
    
    if ([imageArray count]) {

        for (int i = 0; i < imageArray.count; i++) {
            
            UIImage *image = imageArray[i];
            
            //压缩图片
            image = [Utils imageWithImage:image];
            
            UIImageOrientation imageOrientation = image.imageOrientation;
            if (imageOrientation != UIImageOrientationUp) {
                
                UIGraphicsBeginImageContext(image.size);
                [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
                image = UIGraphicsGetImageFromCurrentImageContext();
                UIGraphicsEndImageContext();
            }
            
            imageOrientation = image.imageOrientation;
            
            NSData * fileData = UIImageJPEGRepresentation(image,1);
            
            if (fileData.length > 1024 * 100) {
                fileData = UIImageJPEGRepresentation(image,0.5);
            }
            
            NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
            [dict setObject:@"InsertfileInfo" forKey:@"method"];
            [dict setObject:@"1" forKey:@"typeid"];
            [dict setObject:[fileData base64Encoding] forKey:@"file"];
            [dict setObject:@"11" forKey:@"filename"];
            [dict setObject:@"file" forKey:@"description"];
            [dict setObject:@".jpg" forKey:@"kz"];
            dict  = [Utils completeImageSubmitParameterWith:dict];
            NSString * postValue = [Utils getXMLStringWithParameter:dict];
            
            [Utils submitImageToWebService:SUBMITIMAGEURL SOAPActionSring:@"http://tempuri.org/InsertfileInfo" postValue:postValue success:^(NSInteger recode, id resposeJson){
                
                NSDictionary * dict = (NSDictionary *)resposeJson;
                NSString * returncode = [dict objectForKey:@"returncode"];
                if ([returncode isEqualToString:@"10000"]) {
                    [self hideHud];
//                    [self showHint:NSLocalizedString(@"setting.uploadSuccess", @"uploaded successfully")];
                    [self->imageIdArray addObject:[dict objectForKey:@"id"]];
                    if ([self ->imageArray count] == [self->imageIdArray count]) {
                        [self submitHomework:YES];
                    }
                    return ;
                }else
                {
                    [self hideHud];
                    return ;
                }
            } failure:^(NSInteger recode, NSError * error){
                [self hideHud];
                [self showHint:NSLocalizedString(@"setting.uploadFail", @"uploaded failed")];
                return ;
            }];
            
        }
        
    }else
    {
        if ([ContentTextView.text isEqualToString:@"请编辑动态内容"]) {
            
            [Utils alertViewWithMessage:@"请输入动态内容"];
            return;
        }
        
        if ([[ContentTextView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0)
        {
            [Utils alertViewWithMessage:@"请输入动态内容"];
            return;
        }
        
        if (ContentTextView.text.length>200) {
            [Utils alertViewWithMessage:@"请将动态内容限制在200字以内"];
            return;
        }
        
        [self submitHomework:NO];
    }
}
- (void)submitHomework:(BOOL)submitFile{
    NSUserDefaults *ud=[NSUserDefaults standardUserDefaults];
    NSString *studentId=[ud objectForKey:@"studentID"];
    NSString *classids;
    if (selcetClassidArray.count>0) {
        classids=[selcetClassidArray componentsJoinedByString:@","];
    }else
    {
        return;
    }
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"api_info_add" forKey:@"method"];
    [dict setObject:classids forKey:@"classid"];
    [dict setObject:@"1" forKey:@"type"];  //1表示发送的是动态
    if ([lasttype isEqualToString:@"1"])
    {
        [dict setObject:@"1" forKey:@"isSendMsg"];
        [dict setObject:@"0" forKey:@"studentid"];
    }else
    {
        [dict setObject:@"0" forKey:@"isSendMsg"];
        [dict setObject:@"0" forKey:@"studentid"];
//        if (studentId!=nil) {
//            [dict setObject:studentId forKey:@"studentid"];
//        }else
//        {
//            return;
//        }
        
    }
    [dict setObject:USERID forKey:@"userid"];
    
    if (![ContentTextView.text isEqualToString:@"请编辑动态内容"] && [[ContentTextView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] >0 ) {
        
        [dict setObject:ContentTextView.text forKey:@"scontent"];
        
    }
    
    if (submitFile) {
        NSString *filesString = [imageIdArray componentsJoinedByString:@","];
        [dict setObject:filesString forKey:@"fileid"];
    }
    [Utils post:nil parameters:dict success:^(NSInteger recode, id resposeJson) {
        self->userdict = (NSDictionary *)resposeJson;
        AppDelegate * delegate = (AppDelegate *)CONSTAPPDELEGATE;
        delegate.isChangeRole=@"yes";
        
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [self->_delegate reloadTableViewData];
            [self.navigationController popViewControllerAnimated:YES];
            
//            id num=[self->userdict objectForKey:@"integalnum"];
//            if (![num isKindOfClass:[NSNull class]]) {
//                NSString *n=num;
//                if ([n intValue]>0) {
//                    [self->_yddelegate showYunDouAlert:@"发动态" andNum:[n intValue]];
//                    
//                    
//                }
//            }
        });

        
        
    } failure:^(NSInteger recode, NSError *error) {
        
        [self showHint:@"网络异常,请稍后重试!"];
        
    }];
    
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
//    if (alertView.tag==101) {
//        
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            
//            [self->_delegate reloadTableViewData];
//            [self.navigationController popViewControllerAnimated:YES];
//            
//            id num=[self->userdict objectForKey:@"integalnum"];
//            if (![num isKindOfClass:[NSNull class]]) {
//                NSString *n=num;
//                if ([n intValue]>0) {
//                    [self->_yddelegate showYunDouAlert:@"发动态" andNum:[n intValue]];
//                    
//                    
//                }
//            }
//        });
//        
//    }else
    if (alertView.tag==201) {
        return;
    }else {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
        
        UIViewController * view = nil;
        
        if ([lasttype isEqualToString:@"1"]) {
            view = [storyboard instantiateViewControllerWithIdentifier:@"ClassTeamViewController"];
            
        }
        
        if (view != nil) {
            [self.navigationController pushViewController:view animated:YES];
        }
    }
    
}
#pragma mark -UIActionSheetDelegate
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == 2) { //取消
        return;
    }
    
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    
    imagePicker.allowsEditing = YES;
    
    if (buttonIndex == 0) {  //照相机
        NSString *mediaType = AVMediaTypeVideo;
        
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
        
        if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
            
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的“设置－隐私－相机”中允许访问相机" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            alert.tag=201;
            [alert show];
            
        }else
        {
            
            imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(__bridge NSString *)kUTTypeImage, nil];
            
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:imagePicker animated:YES completion:nil];
        }
        
    }else{   //图库
        
        imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 - imageArray.count delegate:self];
        [self presentViewController:imagePickerVc animated:YES completion:nil];
        
    }
    
    
    
    
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *orgImage = info[UIImagePickerControllerOriginalImage];
    [picker dismissViewControllerAnimated:YES completion:nil];
    if (orgImage != nil) {
        [imageArray addObject:orgImage];
        [self relignmentImageButton];
    }
}

- (void)relignmentImageButton
{
    for (UIView *view in picsBackView.subviews) {
        
        if ([view isKindOfClass:[MenuButton class]]) {
            [view removeFromSuperview];
        }
    }
    
    CGFloat hirizontalGap = 18;
    CGFloat picHeight=(SCREENWIDTH-24-40)/3;
    CGFloat picWidth=(SCREENWIDTH-24-40)/3;
    
    for (NSInteger imageIndex = 0 ; imageIndex <= [imageArray count]; imageIndex ++) {
        CGRect btnRect = CGRectMake(12 + (hirizontalGap + picWidth)* (imageIndex % 3) , 10 + (hirizontalGap + picHeight) * (imageIndex / 3),picWidth, picHeight);
        
        if (imageIndex == [imageArray count]) {
            
            
            if (imageIndex == 9)
            {
                btnRect = CGRectMake(12 + (hirizontalGap + picWidth)* (8 % 3) , 10 + (hirizontalGap + picHeight) * (8 / 3),picWidth, picHeight);
                _takePictureBtn.hidden = YES;
                
            }
            else
            {
                //全部删除图片 picsBackView不显示
                if(imageArray.count==0)
                {
                    _takePictureBtn.hidden = YES;
                    
                    picsBackView.frame=CGRectMake(0, bottomView.frame.origin.y+bottomView.frame.size.height, SCREENWIDTH, 0);
                    
                    
                    _BackScrollView.contentSize=CGSizeMake(SCREENWIDTH, picsBackView.frame.origin.y+picsBackView.frame.size.height+20);
                    
                    addPicView.hidden=NO;
                    picLine.hidden = YES;
                    return;
                }
                
                _takePictureBtn.hidden = NO;
                _takePictureBtn.frame=btnRect;
            }
            
            picsBackView.frame=CGRectMake(0, bottomView.frame.origin.y+bottomView.frame.size.height, SCREENWIDTH, CGRectGetMaxY(btnRect)+10);
            picLine.frame =CGRectMake(12, 0, SCREENWIDTH-12, 0.5);
            picLine.hidden = NO;
            
            
            _BackScrollView.contentSize=CGSizeMake(SCREENWIDTH, picsBackView.frame.origin.y+picsBackView.frame.size.height+20);
            
            return;
        }
        MenuButton * iamgeBtn = [MenuButton buttonWithType:UIButtonTypeCustom];
        [iamgeBtn setFrame:btnRect];
        iamgeBtn.tag = imageIndex;
        [iamgeBtn addTarget:self action:@selector(deletePicture:) forControlEvents:UIControlEventTouchUpInside];
        iamgeBtn.imageView.contentMode = UIViewContentModeScaleAspectFill;
        [iamgeBtn setImage:[imageArray objectAtIndex:imageIndex] forState:UIControlStateNormal];
        
        [picsBackView addSubview:iamgeBtn];
        
        [picsBackView layoutSubviews];
    }
    
}

- (void)deletePicture:(MenuButton *)sender
{
    XZPhotobrowserViewController *vc = [[XZPhotobrowserViewController alloc] init];
    vc.index_Current = sender.tag+1;
    vc.arrayOK = imageArray;
    vc.delegate = self;
    
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark -TZImagePickerDelegate
-(void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets{
    
    [imageArray addObjectsFromArray:photos];
    
    [self relignmentImageButton];
}

#pragma mark -ChangeImageDelegate
-(void)changeImageWithArray:(NSMutableArray *)arr{
    
    [imageArray removeAllObjects];
    [imageArray addObjectsFromArray:arr];
    
    [self relignmentImageButton];
}

#pragma --uitextViewdelegate
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    if ([textView.text isEqualToString:@"请编辑动态内容"]) {
        textView.text=@"";
    }
    
    ContentTextView.textColor=[UIColor blackColor];
    
    
    return YES;
}
//焦点发生改变
-(void)textViewDidChangeSelection:(UITextView *)textView
{

    if (textView.text.length > 200) {
        UITextRange *markedRange = [textView markedTextRange];
        if (markedRange) {
            return;
        }
        //Emoji占2个字符，如果是超出了半个Emoji，用15位置来截取会出现Emoji截为2半
        //超出最大长度的那个字符序列(Emoji算一个字符序列)的range
        NSRange range = [textView.text rangeOfComposedCharacterSequenceAtIndex:200];
        textView.text = [textView.text substringToIndex:range.location];
    }
    
    NSString *str=[NSString stringWithFormat:@"请将您的文字限制在200字以内 %lu/200",(unsigned long)textView.text.length];
    
    NSMutableAttributedString *string=[[NSMutableAttributedString alloc]initWithString:str];
    
    if (textView.text.length>190&&textView.text.length<999) {
        [string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(16,3)];
    }
    WordCountLabel.attributedText=string;
}

//结束编辑
- (void)textViewDidEndEditing:(UITextView *)textView
{
    ContentTextView.scrollEnabled = NO;
    if (textView.text.length==0) {
        
        ContentTextView.text=@"请编辑动态内容";
        ContentTextView.textColor=[UIColor lightGrayColor];
        WordCountLabel.text=[NSString stringWithFormat:@"请将您的文字限制在200字以内 %@/200" ,@"0"];
        
    }
}

//限制EMOJI键盘输入
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    
    // 不让输入表情
    if ([textView isFirstResponder]) {
        
        
        if ([[[textView textInputMode] primaryLanguage] isEqualToString:@"emoji"] || ![[textView textInputMode] primaryLanguage]) {
           
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"不能输入表情" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil,nil];
            [alertView show];
            return NO;
        }
        
    }
    return YES;
}

        
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
